<script setup>
import pageContainer from '@/components/pageContainer.vue';
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus,Check } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores';
import {userPeopleImgService} from '@/api/user'
//数据绑定
const {user:user_pic}=useUserStore()
const imageUrl=ref(user_pic)
const uploadRef=ref()
const userStore=useUserStore()
//函数
const checkImg=()=>{
    uploadRef.value.$el.querySelector('input').click()
}
const onSelectFile = (file) => {
    const reader = new FileReader();
    reader.readAsDataURL(file.raw); // 将文件读取为 DataURL(Base64)
    reader.onload = () => {
        imageUrl.value = reader.result; // 将 Base64 数据存入 imageUrl
        ElMessage.success('本地图片正在预览....');
    };
    reader.onerror = () => {
        ElMessage.error('图片加载失败，请重试');
    };
};
const uploadImg = async () => {
    try {
      await userPeopleImgService({ avatar: imageUrl.value });
      
        ElMessage.success('呕，好丑');
        userStore.getUser()
    } catch (error) {
        ElMessage.error(error.message || '头像上传失败，请重试');
        console.error('上传头像失败:', error);
    }
};
</script>

<template>


    <pageContainer title="头像更换中心">
        <el-upload
        ref="uploadRef"
    class="avatar-uploader"
    :show-file-list="false"
    :auto-upload="false"
    :on-change="onSelectFile"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
<el-button type="primary" :icon="Plus" @click="checkImg">选择图片</el-button>
<el-button type="success" :icon="Check" @click="uploadImg">上传头像</el-button>

    </pageContainer>
</template>

<style scoped>
.avatar-uploader {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  width: 178px;
  height: 178px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  background-color: #f5f5f5;
  transition: border-color 0.3s;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 6px;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.el-button {
  margin-top: 20px;
  margin-right: 10px;
}

.page-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
}
</style>